package com.guigu.www.utils;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

import java.io.IOException;
import java.io.InputStream;

public class FtpUtil {
    // ftp服务器ip地址
    private static final String FTP_ADDRESS = "139.224.190.249";
    // 端口号
    private static final int FTP_PORT = 21;
    // 用户名
    private static final  String FTP_USERNAME = "TM";
    // 密码
    private static final String FTP_PASSWORD = "18574641800";
    // 附件路径
    private static final String FTP_BASEPATH = "/home/TM/files";

    public static boolean uploadFile (String fileName, InputStream input) {
        boolean success = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(FTP_ADDRESS,FTP_PORT);// 连接FTP服务器
            ftp.login(FTP_USERNAME,FTP_PASSWORD);// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)){
                ftp.disconnect();
                return false;
            }
            ftp.setControlEncoding("utf-8");
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            fileName=new String(fileName.getBytes("UTF-8"),"iso-8859-1");
            ftp.makeDirectory(FTP_BASEPATH);
            ftp.changeWorkingDirectory(FTP_BASEPATH);
            ftp.enterLocalPassiveMode();
            ftp.storeFile(fileName,input);
            input.close();
            ftp.logout();
            success = true;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (ftp.isConnected()){
                try {
                    ftp.disconnect();
                }catch (IOException ioException){
                    ioException.printStackTrace();
                }
            }
        }
        return success;
    }
}
